<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Title</title>
    <script src="./lib/vue.js"></script>
    <link rel="stylesheet" href="./lib/bootstrap.min.css">
</head>
<body>
<!--Vue实例所控制的这个元素区域，就是我们的V-->
<div id="app">
    <cmt-box @func="loadComments"></cmt-box>
    <ul class="list-group">
        <li class="list-group-item" v-for="item in list" :key="item.id">
            <span class="badge">评论人：{{item.user}}</span>
            {{item.content}}
        </li>
    </ul>
</div>
<template id="tmpl">
    <div>
        <div class="form-group">
            <label>评论人：</label>
            <input type="text" class="form-control" v-model="user">
        </div>
        <div class="form-group">
            <label>评论内容：</label>
            <textarea class="form-control" v-model="content"></textarea>
        </div>
        <div class="form-group">
            <input type="button" value="发表评论" class="btn btn-primary" @click="postComment">
        </div>
    </div>
</template>
<script>
    var commentBox = {
        template: '#tmpl',
        data() {
            return {
                user: '',
                content: '',
            }
        },
        methods: {
            postComment() { //发表评论的方法
                // 分析：发表评论的业务逻辑
                // 评论数据存在localstorage中
                // localstorage 只支持存放 字符串 数据
                var comment = {id: Date.now(), user: this.user, content: this.content}
                // 从localStorage中获取所有的评论
                var list = JSON.parse(localStorage.getItem('cmts') || '[]')
                list.push(comment)
                localStorage.setItem('cmts', JSON.stringify(list))
                this.user = this.content = ''
                this.$emit('func')
            }
        }
    }
    // 创建Vue实例，得到ViewModel
    var vm = new Vue({
        el: '#app',
        data: {
            list: [
                {id: Date.now(), user: '李白', content: '天生我材必有用'},
                {id: Date.now(), user: '杜甫', content: '百年多病独登台'},
                {id: Date.now(), user: '李商隐', content: '君问归期未有期'},
            ]
        },
        created() {
            this.loadComments()
        },
        methods: {
            loadComments() {
                var list = JSON.parse(localStorage.getItem('cmts') || '[]')
                this.list = list
            }
        },
        components: {
            'cmt-box': commentBox
        }
    })
</script>
</body>
</html>